import { ref } from 'vue'
import { storeToRefs } from 'pinia'
import { useRouter } from 'vue-router'
import { useLocalStorageStore } from '@/stores/localStore'
import { useCurrActStroe } from '@/stores/currActStore'
import { useSocketStore } from '@/stores/socketStore'
export default function () {
  const router = useRouter()
  // 用户数据
  const { currUser } = storeToRefs(useCurrActStroe())
  const { assignCurrUser } = useCurrActStroe()
  //   头像链接
  const changeImgUrl = ref('/src/components/icons/fontImg/User.png')
  //   上传图片转url
  function uploadImg(e: HTMLInputElement) {
    const file = e.files
    if (file) {
      changeImgUrl.value = URL.createObjectURL(file[0])
    }
  }
  //   收集更改用户信息的表单
  const form = ref<HTMLFormElement | null>()
  const formSet = ref<Set<HTMLInputElement>>(new Set())
  function getUserFormData() {
    const formData = new FormData()
    formSet.value.forEach((input: HTMLInputElement) => {
      if (input.type === 'file' && input.files) {
        formData.append(input.name, input.files[0])
      } else {
        if (input.value.trim()) {
          formData.append(input.name, input.value)
        }
      }
    })
    return formData
  }

  const { removeToken } = useLocalStorageStore()
  const { removeCurrUser } = useCurrActStroe()
  function logOut() {
    const { userLogout } = useSocketStore()
    router.replace({ name: 'login' })
    removeToken()
    removeCurrUser()
    userLogout()
  }
  return {
    form,
    changeImgUrl,
    currUser,
    formSet,
    uploadImg,
    getUserFormData,
    assignCurrUser,
    logOut
  }
}
